package com.blue.rpc.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.blue.rpc.core.message.RpcRequest;
import com.blue.rpc.core.message.RpcResponse;
import com.blue.rpc.util.RpcServerUtil;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 心跳处理器
 * 
 * @author zhengj
 * @since 1.0 2017年3月13日
 */
public class HeartbeatHandler extends SimpleChannelInboundHandler<RpcRequest>
{
	private static Logger logger = LoggerFactory.getLogger(HeartbeatHandler.class);
	
	public HeartbeatHandler()
	{
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, RpcRequest request) throws Exception
	{
		if (RpcServerUtil.isHeartbeat(request)) // 是心跳报文
		{
			logger.debug("收到 ping：{}", request.getRequestId());
			RpcResponse response = RpcServerUtil.create(request);
			ctx.writeAndFlush(response);
			return;
		}
		ctx.fireChannelRead(request);
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception
	{
		super.userEventTriggered(ctx, evt);
		
		if (evt instanceof IdleStateEvent)
		{
			IdleStateEvent event = (IdleStateEvent)evt;
			switch (event.state())
			{
				case READER_IDLE:
					logger.debug("读空闲");
					ctx.close();
					break;
				default:
					break;
			}
		}
	}
	
}
